//
//  AddAttendanceViewController.m
//  RSW.IOS
//
//  Created by zhaiqiuqiu on 17/1/2.
//  Copyright © 2017年 com.xtion.crm. All rights reserved.
//

#import "AddAttendanceViewController.h"
#import "AttendanceDynamicCellConstraintFactory.h"
#import "ChoiceRecordViewController.h"
#import "KZVideoConfig.h"
#import "ChoiceVoiceViewController.h"

NSString *const AddAttendanceViewControllerTitleParamKey = @"AddAttendanceViewControllerTitleParamKey";

@interface AddAttendanceViewController ()<SimpleActionSheetViewDelegate,XLGPositioningHelperDelegate>
{
    NSMutableArray *_typeData;
    NSString *_typeId;
    
    RSWDataOperation *_manager;
    
    UIActivityIndicatorView *_activityView;
    NSString *_address;
    CLLocationCoordinate2D _coor;
    
    BOOL _success;
    
    KZVideoModel *_model;
    NSString *_voicePath;
}
@end

@implementation AddAttendanceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self checkSession];
    
    NSString *title = self.param[AddAttendanceViewControllerTitleParamKey];
    [self setBackNavigateItemTitle:title];
    
    _typeData = [NSMutableArray new];
    _typeId = @"";
    
    _address = @"";
    _coor = CLLocationCoordinate2DMake(0, 0);
    [XLGServiceTime verifyTime:NO];
    [XLGPositioningHelper getCoordWithReceiver:self completion:NULL];
    _success = NO;
    
    _manager = [[RSWDataOperation alloc]initWithDataOperationManagerDelegate:self];
    
    _vclType = DynamicColumnFieldViewTypeAdd;
    _transformMap = [AttendanceInfo JSONObjectProperty:nil];
    _constraint = [AttendanceDynamicCellConstraintFactory factoryForModify:nil];
    
    [super initViewDidLoad];
    [super reloadDyanmicField];
    
    [_manager getMyAttendanceTypeCompletion:^(NSInteger nResult, NSArray *list, NSError *error)
     {
         [_typeData addObjectsFromArray:list];
     }];
}

- (CGFloat)dynamicColumnFieldCore:(DynamicColumnFieldCore *)dynamicColumnFieldCore heightForHeaderInGroup:(NSInteger)group
{
    return 10;
}

#pragma mark --
#pragma mark -- override

-(void)didSelectedSwitchSelectGroupTableCell:(FieldDescript *)fieldDescript
{
    if([fieldDescript.fieldName isEqualToString:@"TypeId"])
    {
        [SimpleActionSheetView actionSheetViewWithTitle:@"考勤类型" data:_typeData delegate:self];
    }
}

-(void)dynamicColumnFieldCore:(DynamicColumnFieldCore *)dynamicColumnFieldCore dynamicColumnCell:(ExpandDynamicCell *)cell didCreate:(FieldDescript *)fieldDescript
{
    if([cell.szTag isEqualToString:@"Address"])
    {   
        TextAreaGroupTableViewCell *c = (TextAreaGroupTableViewCell *)cell;
        c.userInteractionEnabled = NO;
        
        if(_activityView == nil)
            _activityView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [cell.contentView addSubview:_activityView];
        
        _activityView.hidden = YES;
        [_activityView stopAnimating];
        _activityView.top = c.bottom + 10;
        
        if([XLGPositioningHelper locationServiceVisible] == NO)
            c.text = @"请为本应用开启定位权限";
        else if([XLGPositioningHelper isNetworkReachable] == NO)
            c.text = @"请检查网络";
        else if([_address isEqualToString:@"-1"])
            c.text = @"定位失败，请重试";
        else if(_address.length >0)
            c.text = _address;
        else
        {
            c.text = @"正在定位……";
            _activityView.hidden = NO;
            [_activityView startAnimating];
        }
    
        _activityView.left = 13;
    }
    else if([cell.szTag isEqualToString:@"Longitude"])
    {
        TextInputGroupTableViewCell *c = (TextInputGroupTableViewCell *)cell;
        c.userInteractionEnabled = NO;
        c.text = [NSString stringWithFormat:@"%f", _coor.longitude];
    }
    else if([cell.szTag isEqualToString:@"Latitude"])
    {
        TextInputGroupTableViewCell *c = (TextInputGroupTableViewCell *)cell;
        c.userInteractionEnabled = NO;
        c.text = [NSString stringWithFormat:@"%f", _coor.latitude];
    }
}

#pragma mark --
#pragma mark -- SimpleActionSheetViewDelegate
- (void)actionSheetView:(SimpleActionSheetView *)actionSheetView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(_typeData.count >0)
    {
        SimpleActionSheetInfo * singleSwitchValue = [_typeData objectAtIndex:indexPath.row];
        
        SwitchSelectGroupTableViewCell *cell = (SwitchSelectGroupTableViewCell*)[_core expandDynamicCellWithTag:@"TypeId"];
        cell.text = singleSwitchValue.name;
        _typeId = singleSwitchValue.dataId;
        
        cell.showClearButton = YES;
    }
}

#pragma mark --
#pragma mark -- ClearButton
-(void)dynamicColumnFieldCore:(DynamicColumnFieldCore *)dynamicColumnFieldCore didClickedClearButtonOfDropDownGroupTableViewCell:(DropDownGroupTableViewCell *)cell
{
    if([cell.szTag isEqualToString:@"TypeId"])
    {
        cell.text = @"";
        cell.showClearButton = NO;
    }
}

-(void)clickedRightBarButton:(id)sender
{
    [UIViewController closeKeyBoard];
    
    if(_success == NO)
    {
        [UIAlertView showErrorMsg:@"定位失败，请重试"];
        return;
    }
    
    if([super verifyDynamicField:_constraint] == YES)
    {
        AttendanceInfo *modelInfo = [AttendanceInfo emptyAttendanceInfo];
        
        XMSQueueDictionary *qdSet = _transformMap;
        
        [super extractDynamicFieldValue:_constraint transformMap:qdSet packObj:modelInfo specialExtract:^BOOL(FieldDescript *fixField)
         {
             return NO;
         }];
        
        modelInfo.typeId = _typeId;
        NSArray *ar = [modelInfo.address componentsSeparatedByString:@";"];
        if(ar.count == 3)
        {
            modelInfo.longitude = ar[0];
            modelInfo.latitude = ar[1];
            modelInfo.address = ar[2];
        }
        
        [_manager addAttendance:modelInfo completion:^(NSInteger nResult, BOOL bReslut, NSError *error)
         {
             [super filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
              {
                  switch (nResult)
                  {
                      case YES:
                      {
                          if(bReslut == YES)
                          {
                              [XUIAlertView alertViewWithTitle:@"提示" message:@"保存成功" cancelButtonTitle:nil otherButtonTitles:@[@"确定"] clickBlock:^(NSInteger nClickindex)
                               {
                                   [XUINavigationController pop];
                               }];
                          }
                          else
                          {
                              if(error.domain.length > 0)
                                  [UIAlertView showErrorMsg:error.domain];
                              else
                                  [UIAlertView showErrorMsg:@"保存失败"];
                          }
                          
                          break;
                      }
                      default:
                      {
                          [UIAlertView showErrorMsg:@"保存失败"];
                          break;
                      }
                  }
              }];
         }];
    }
}

#pragma mark --
#pragma mark -- bmkLocation delegate

-(void)positioningHelperUpdateCoord:(CLLocation *)location userInfo:(id)userInfo error:(NSError *)error
{
    if(error == nil)
    {
        if([XLGPositioningHelper isNetworkReachable])
        {
            [XLGPositioningHelper getAddrWithReceiver:self coordinate:location.coordinate completion:NULL];
            
            return;
        }
        else
        {
            [UIAlertView showErrorMsg:XUIViewControllerBusinessDataRequestNetWorkOfflineTip];
        }
    }
    else
    {
        _coor = CLLocationCoordinate2DMake(0, 0);
        _address = @"-1";
        
        [super reloadDyanmicField];
    }
}

-(void)positioningHelperUpdateAddr:(id<XLGPositingReverseGeoCodeResult>)addr userInfo:(id)userInfo error:(NSError *)error
{
    if(error == nil)
    {
        if(addr.address.length >0)
        {
            _address = addr.address;
            _success = YES;
        }
        else
            _address = @"未知地址";
        
        _coor = addr.location;
        
        [XLGPositioningHelper cancelGetAddrWithReceiver:self];
    }
    else
    {
        [XLGPositioningHelper cancelReceiver:self];
        
        _coor = CLLocationCoordinate2DMake(0, 0);
        _address = @"-1";
    }
    
    [super reloadDyanmicField];
}

#pragma mark --
#pragma mark -- recv last viewController param

-(void)recvPopViewControllerSwitchParam:(XUIViewControllerSwitchParam *)switchParam
{
    if(switchParam.param[ChoiceCurrentPositionViewControllerChoicPositionParamKey] != nil)
    {
        //NSString *selectAddress = switchParam.param[ChoiceCurrentPositionViewControllerChoicPositionParamKey];
        //NSArray *ar = [selectAddress componentsSeparatedByString:@";"];
    }
    else if(switchParam.param[ChoiceRecordViewControllerChoiceRecordParamKey] != nil)
    {
        _model = switchParam.param[ChoiceRecordViewControllerChoiceRecordParamKey];
        
        NSLog(@"%@",_model.videoAbsolutePath);
        
        MixedPanelGroupTableViewCell *cell = (MixedPanelGroupTableViewCell*)[_core expandDynamicCellWithTag:@"Images"];
        
        UIImage *img = [UIImage imageNamed:@"img_video_default"];
        [cell addImage:img withTag:_model.videoAbsolutePath];
    }
    else if(switchParam.param[ChoiceVoiceViewControllerChoiceVoiceParamKey] != nil)
    {
        _voicePath = switchParam.param[ChoiceVoiceViewControllerChoiceVoiceParamKey];
        
        NSLog(@"%@",_voicePath);
        
        MixedPanelGroupTableViewCell *cell = (MixedPanelGroupTableViewCell*)[_core expandDynamicCellWithTag:@"Images"];
        
        UIImage *img = [UIImage imageNamed:@"img_voice_default"];
        [cell addImage:img withTag:_voicePath];
    }
    else
        [super recvPopViewControllerSwitchParam:switchParam];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
